package com.neusoft.service.impl;

import com.neusoft.mapper.RedPacketMapper;
import com.neusoft.po.RedPacket;
import com.neusoft.po.RedPacketList;
import com.neusoft.service.RedPacketService;
import com.neusoft.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class RedPacketServiceImpl implements RedPacketService {
    @Autowired
    private RedPacketMapper redPacketMapper;
    
    @Override
    public RedPacket getTheRedPacketByPacketId(int packetId) {
    	return redPacketMapper.getRedPacketByPacketId(packetId);
    };
    
    @Override
    public int deleteAllRedPacketByPacketId(int packetId) {
    	int result = redPacketMapper.deleteRedPacketByPacketId(packetId);
    	redPacketMapper.deleteRedPacketCopyByPacketId(packetId);
    	return result;
    };
    
    @Override
    public List<RedPacket> getAvailableRedPacketByUserId(String userId) {
        List<RedPacket> list = redPacketMapper.getTotalRedPacketByUserId(userId);
        List<RedPacket> returnlist = new ArrayList<>();
        //将list中所有expierdTime小于当前时间的积分删除
        for (RedPacket redPacket : list) {
            if (CommonUtil.compareDate(redPacket.getExpiredTime(), CommonUtil.getCurrentDate1()) == 1) {
                returnlist.add(redPacket);
            } else {
                redPacketMapper.deleteRedPacketCopyByPacketId(redPacket.getPacketId());
            }
        }
        return returnlist;
    }

    @Override
    public List<RedPacket> getRedPacketByUserId(String userId) {
        return redPacketMapper.getRedPacketByUserId(userId);
    }

    @Override
    public List<RedPacket> getRedPacketByUserIdAndChannelType(String userId, int channelType) {
        return redPacketMapper.getRedPacketByUserIdAndChannelType(userId, channelType);
    }

    @Override
    public int insertRedPacket(RedPacket redPacket) {
        redPacket.setCreateTime(CommonUtil.getCurrentDate1());
        if (redPacket.getNum() >= 0) {
        	redPacket.setExpiredTime(CommonUtil.getCurrentDate2());
        	redPacketMapper.insertRedPacketCopy(redPacket);
        } else {
            Double left = -redPacket.getNum();
            List<RedPacket> list = redPacketMapper.getTotalRedPacketByUserId(redPacket.getUserId());
            RedPacketList redPacketList = new RedPacketList(list);
            RedPacket UpdateRedPacket = redPacketList.getUpdatedRedPacket(left);
            System.out.println(UpdateRedPacket.getPacketId());
            System.out.println(UpdateRedPacket.getNum());
            redPacketMapper.updateRedPacketCopyByPacketId(UpdateRedPacket.getPacketId(), UpdateRedPacket.getNum());
            for (RedPacket redPacket2 : redPacketList.getDeletedList()) {
            	redPacketMapper.deleteRedPacketCopyByPacketId(redPacket2.getPacketId());
            }
        }
        return redPacketMapper.insertRedPacket(redPacket);
    }
}
